import React, {  useState, useRef } from 'react';
import { connect, Dispatch } from 'umi';

import { Drawer, Button, message, Input, Form } from 'antd';
import moment from 'moment';

import DateFilter from './DateFilter';
import FilterValueSelect from './FilterValueSelect';

import {
  IndexDetailItem,
  IFilter,
  ICostCenter,
  IDepartment,
  ISubject,
  ICustomFilter,
} from '@/pages/SelfQuery/type';
import { ConnectState } from '@/models/connect';

import { VISUALTYPES, FILTER_OPERATOR, DATA_ACTION_TYPE } from '@/pages/SelfQuery/constants';
import { isLevelVisualType } from '@/pages/SelfQuery/utils';
import { OperatorFilterTypes } from './constants';

interface CustomFiltersProps {
  visible: boolean;
  setVisible: any;
  dispatch: Dispatch;
  indexDetail: IndexDetailItem;
  costCenters: ICostCenter[];
  departments: IDepartment[];
  subjects: ISubject[];
  formFilters: IFilter[];
  loading?: boolean;
}

const CustomFilters: React.FC<CustomFiltersProps> = (props) => {
  const {
    visible,
    setVisible,
    indexDetail,
    costCenters,
    subjects,
    departments,
    formFilters,
    loading,
    dispatch,
  } = props;
  const [formFiltersState, setFormFiltersState] = useState<IFilter[]>([]); // 筛选表单值的集合

  // 各类型DOM对象 重置时使用
  const departmentRef = useRef<any>();
  const subjectRef = useRef<any>();
  const costCenterRef = useRef<any>();
  const dateRef = useRef<any>();
  const [form] = Form.useForm();
  let existFrom = false; // 是否存在能够重置的from实例

  // 合并筛选过滤器
  const onCustomSelectFilter = (key: string, filters: IFilter[] | undefined) => {
    let formFilters: Array<any> = [...formFiltersState];
    if (!filters || !filters.length) {
      formFilters = formFilters.filter((v: any) => v.name != key);
      setFormFiltersState(formFilters);
      return;
    }
    //是否存在 先剔除该类型，再添加
    if (formFilters.filter((val: any) => val.name == key).length > 0) {
      formFilters = formFilters.filter((val: any) => val.name != key);
      formFilters = formFilters.concat(filters);
    } else {
      formFilters = formFilters.concat(filters);
    }
    setFormFiltersState(formFilters);
  };

  // 输入框的值发生改变回调
  const formValueChange = (event: any, customFilter: any) => {
    const value = event.target.value;
    let formFilters: Array<any> = [...formFiltersState];
    const { name } = customFilter;
    if (!value) {
      formFilters = formFilters.filter((v: any) => v.name != name);
      setFormFiltersState(formFilters);
      return;
    }
    buildCustomFilter(customFilter, value);
  };

  const buildCustomFilter = (customFilter: ICustomFilter, value: any) => {
    let { name, visualType } = customFilter;
    let formFilters: Array<any> = [...formFiltersState];
    //过滤空值
    if (!value || value == '') {
      setFormFiltersState(formFilters.filter((v: any) => v.name != name));
      return;
    }
    // if (isLevelVisualType(visualType)) {
    //   //获取长路径的叶子节点名称
    //   column = `regexp_extract(${name}, '[^-|_]+$',0)`
    // }
    //action:'CUSTOM_FILTER'，标识自定义过滤，
    const filter: IFilter = {
      name,
      operator: OperatorFilterTypes.Regexp,
      type: 'filter',
      value,
      sqlType: 'STRING',
      action: DATA_ACTION_TYPE.filter,
      visualType: isLevelVisualType(visualType) ? visualType : VISUALTYPES.String,
      isCustomFilter: true, //标识是自定义表单的过滤
    };
    //是否存在
    if (formFilters.filter((val: any) => val.name == name).length > 0) {
      formFilters = formFilters.map((val: any) => (val.name == name ? filter : val));
    } else {
      formFilters.push(filter);
    }
    setFormFiltersState(formFilters);
  };

  // 获取筛选默认值
  const getValue = (formFilters: IFilter[]) => {
    if (!formFilters.length) {
      return '';
    }
    let results: any = [];
    formFilters.map((v) => {
      const { operator, value, visualType } = v;
      let result = '';
      if (operator == FILTER_OPERATOR.BETWEEN && visualType == VISUALTYPES.Date) {
        result = `${value[0].replace(/'/g, '').slice(0, 10)},${value[1]
          .replace(/'/g, '')
          .slice(0, 10)}`;
      } else {
        // result = getLastLevelVisualTypeVal(value);
        result = value;
      }
      result = result.replace(/%/g, '');
      if (operator == FILTER_OPERATOR.BETWEEN && visualType == VISUALTYPES.Date) {
        const dateArr: Array<string> = result.split(',');
        if (dateArr.length > 0) {
          results = [moment(dateArr[0], 'YYYY-MM-DD'), moment(dateArr[1], 'YYYY-MM-DD')];
        }
      } else {
        results.push(result);
      }
    });
    return results;
  };

  // 重置
  const onReset = () => {
    if (departmentRef.current) {
      departmentRef.current.clear();
    }
    if (subjectRef.current) {
      subjectRef.current.clear();
    }
    if (costCenterRef.current) {
      costCenterRef.current.clear();
    }
    if (dateRef.current) {
      dateRef.current.clear();
    }
    if (existFrom) {
      form.resetFields();
    }
    setFormFiltersState([]);

    dispatch({
      type: 'widget/fetchData',
      payload: { type: DATA_ACTION_TYPE.filter, pararms: { filters: [] } },
      callback: (res) => {
        if (res) {
          message.success('重置成功');
        } else {
          message.warning('重置失败');
        }
      },
    });
  };

  // 过滤
  const onFilter = () => {
    //过滤所有非自定义查询的值
    let newformFilters = formFilters.filter((f) => !f.isCustomFilter);
    dispatch({
      type: 'widget/fetchData',
      payload: {
        type: DATA_ACTION_TYPE.filter,
        pararms: { filters: [...newformFilters, ...formFiltersState] },
      },
      callback: (res) => {
        if (res) {
          message.success('筛选成功');
        } else {
          message.warning('筛选失败');
        }
        setVisible(false);
      },
    });
  };

  return (
    <Drawer
      destroyOnClose
      title="报表筛选"
      placement="right"
      width="326"
      closable={false}
      onClose={() => {
        setVisible(false);
      }}
      visible={visible}
      footer={
        <div
          style={{
            textAlign: 'center',
          }}
        >
          <Button style={{ marginRight: 20 }} onClick={onReset}>
            重置
          </Button>
          <Button type="primary" htmlType="submit" onClick={onFilter} loading={loading}>
            过滤
          </Button>
        </div>
      }
    >
      {indexDetail.configs.customFilters &&
        indexDetail.configs.customFilters.map((filter: any, index: any) => {
          let { name, field, visualType } = filter;
          // 是否为可编辑输入框
          const { alias } = field;
          const text = alias == '' ? name : alias;
          // 假如存在筛选条件，赋值到默认值
          const formFiltersList = formFilters ? formFilters.filter((v: any) => v.name == name) : [];
          let value = getValue(formFiltersList); // 筛选默认值 之前已经筛选的条件
          let filtersTimeType: any = '自定义';
          if (visualType === VISUALTYPES.Date && formFiltersList.length > 0) {
            filtersTimeType = formFiltersList[0].label;
          }
          let options: Array<{ value: any; label: string }> = []; // 下拉选择数据
          switch (visualType) {
            case VISUALTYPES.Date: // 日期选择
              return (
                <DateFilter
                  ref={dateRef}
                  cRef={dateRef}
                  onCustomSelectFilter={onCustomSelectFilter}
                  name={name}
                  text={text}
                  key={index}
                  defaultType={filtersTimeType}
                  defaultValue={value ? value : []}
                />
              );
            case VISUALTYPES.Department: // 部门选择
              options = departments.map((v) => {
                return { value: v.displayName, label: v.name };
              });
              return (
                <FilterValueSelect
                  ref={departmentRef}
                  cRef={departmentRef}
                  key={index}
                  name={name}
                  visualType={visualType}
                  text={text}
                  options={options}
                  defaultValue={value ? value : []}
                  onFilter={onCustomSelectFilter}
                />
              );
            case VISUALTYPES.Subject: // 主题选择
              options = subjects.map((v) => {
                // value添加上ID,解决数据重复出现相同value报错问题
                return { value: `${v.subjectLongName}(${v.iD})`, label: v.subjectName };
              });
              return (
                <FilterValueSelect
                  ref={subjectRef}
                  cRef={subjectRef}
                  key={index}
                  name={name}
                  visualType={visualType}
                  text={text}
                  options={options}
                  defaultValue={value ? value : []}
                  onFilter={onCustomSelectFilter}
                />
              );
            case VISUALTYPES.CostCenter: // 成本选择
              options = costCenters.map((v) => {
                return { value: v.departmentLongName, label: v.departmentName };
              });
              return (
                <FilterValueSelect
                  ref={costCenterRef}
                  cRef={costCenterRef}
                  key={index}
                  name={name}
                  visualType={visualType}
                  text={text}
                  options={options}
                  defaultValue={value ? value : []}
                  onFilter={onCustomSelectFilter}
                />
              );
            default:
              existFrom = true;
              // 输入框方式
              return (
                <Form key={index} form={form}>
                  <Form.Item label={text} name={name}>
                    <Input
                      placeholder={text}
                      onChange={(event) => {
                        formValueChange(event, filter);
                      }}
                    />
                  </Form.Item>
                </Form>
              );
          }
        })}
    </Drawer>
  );
};

export default connect(({ widget, loading }: ConnectState) => ({
  indexDetail: widget.indexDetail,
  costCenters: widget.costCenters,
  departments: widget.departments,
  subjects: widget.subjects,
  formFilters: widget.formFilters,
  loading: loading.effects['widget/fetchData'],
}))(CustomFilters);
